<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { page } from '$app/stores';
  import { getTaskStatus, getReportUrl } from '$lib/api';
  import type { TaskInfo, Framework } from '$lib/types';

  let taskInfo: TaskInfo | null = null;
  let loading = true;
  let error: string | null = null;
  let pollingInterval: number | null = null;
  let taskComplete = false;

  // 分组框架
  let frameworksByCategory: {[key: string]: Framework[]} = {};

  // 任务ID
  const taskId = $page.params.id;

  // 轮询任务状态
  async function pollTaskStatus() {
    try {
      const status = await getTaskStatus(taskId);
      taskInfo = status;
      
      // 如果任务完成，停止轮询
      if (status.status === 'completed' || status.status === 'failed') {
        taskComplete = true;
        stopPolling();
        
        // 如果有结果，对框架按类别分组
        if (status.status === 'completed' && status.result) {
          const frameworks = status.result.frameworks || [];
          
          // 按类别分组
          frameworksByCategory = frameworks.reduce((groups: {[key: string]: Framework[]}, framework) => {
            const category = framework.category || '其他';
            if (!groups[category]) {
              groups[category] = [];
            }
            groups[category].push(framework);
            return groups;
          }, {});
        }
      }
      
      loading = false;
    } catch (e) {
      error = e instanceof Error ? e.message : '获取任务状态失败';
      loading = false;
    }
  }

  // 开始轮询
  function startPolling() {
    pollTaskStatus();
    pollingInterval = setInterval(pollTaskStatus, 3000) as unknown as number;
  }

  // 停止轮询
  function stopPolling() {
    if (pollingInterval !== null) {
      clearInterval(pollingInterval);
      pollingInterval = null;
    }
  }

  // 获取状态标签类
  function getStatusClass(status: string): string {
    switch (status) {
      case 'completed': return 'status-completed';
      case 'failed': return 'status-failed';
      case 'processing': return 'status-processing';
      default: return 'status-pending';
    }
  }

  // 获取报告URL
  function getHtmlReportUrl() {
    return getReportUrl(taskId, 'html');
  }

  function getJsonReportUrl() {
    return getReportUrl(taskId, 'json');
  }

  // 格式化时间
  function formatDateTime(dateTimeStr: string): string {
    try {
      const date = new Date(dateTimeStr);
      return date.toLocaleString('zh-CN');
    } catch (e) {
      return dateTimeStr;
    }
  }

  // 组件挂载时开始轮询
  onMount(() => {
    startPolling();
  });

  // 组件卸载时停止轮询
  onDestroy(() => {
    stopPolling();
  });
</script>

<svelte:head>
  <title>分析任务 {taskId}</title>
</svelte:head>

<div class="task-container">
  <header>
    <div class="back-link">
      <a href="/">← 返回首页</a>
    </div>
    <h1>应用分析任务</h1>
  </header>

  {#if loading && !taskInfo}
    <div class="loading">
      <div class="spinner"></div>
      <p>正在加载任务信息...</p>
    </div>
  {:else if error}
    <div class="error-card">
      <h2>发生错误</h2>
      <p>{error}</p>
      <button on:click={startPolling}>重试</button>
    </div>
  {:else if taskInfo}
    <div class="task-card">
      <div class="task-header">
        <h2>任务ID: {taskInfo.task_id}</h2>
        <div class="task-meta">
          <div class="status-badge {getStatusClass(taskInfo.status)}">
            {taskInfo.status === 'pending' ? '等待中' : 
             taskInfo.status === 'processing' ? '分析中' : 
             taskInfo.status === 'completed' ? '已完成' : '失败'}
          </div>
          <div class="task-time">
            <div>创建时间: {formatDateTime(taskInfo.created_at)}</div>
            <div>更新时间: {formatDateTime(taskInfo.updated_at)}</div>
          </div>
        </div>
      </div>

      {#if taskInfo.status === 'processing' || taskInfo.status === 'pending'}
        <div class="progress-section">
          <div class="progress-bar">
            <div class="progress-inner"></div>
          </div>
          <p>正在分析应用，请稍候...</p>
        </div>
      {:else if taskInfo.status === 'failed'}
        <div class="error-section">
          <h3>分析失败</h3>
          <p>{taskInfo.error || '未知错误'}</p>
        </div>
      {:else if taskInfo.status === 'completed' && taskInfo.result}
        <div class="result-section">
          <div class="summary-section">
            <h3>分析结果摘要</h3>
            <pre>{taskInfo.result.summary}</pre>
          </div>

          <div class="frameworks-section">
            <h3>检测到的框架 ({taskInfo.result.frameworks_count})</h3>
            
            {#if taskInfo.result.frameworks_count === 0}
              <p>未检测到任何框架</p>
            {:else}
              {#each Object.entries(frameworksByCategory) as [category, frameworks]}
                <div class="category-group">
                  <h4>{category}</h4>
                  <div class="frameworks-grid">
                    {#each frameworks as framework}
                      <div class="framework-card">
                        <div class="framework-header">
                          <h5>{framework.name}</h5>
                          <div class="confidence-badge" 
                               style="background-color: {framework.confidence > 80 ? '#4caf50' : 
                                                        framework.confidence > 50 ? '#ff9800' : '#f44336'}">
                            {framework.confidence}%
                          </div>
                        </div>
                        <div class="framework-version">版本: {framework.version || '未知'}</div>
                        
                        {#if framework.features && framework.features.length > 0}
                          <div class="framework-features">
                            <strong>特性:</strong>
                            <div class="feature-tags">
                              {#each framework.features as feature}
                                <span class="feature-tag">{feature}</span>
                              {/each}
                            </div>
                          </div>
                        {/if}
                        
                        {#if framework.related_frameworks && framework.related_frameworks.length > 0}
                          <div class="related-frameworks">
                            <strong>相关框架:</strong>
                            <div class="related-tags">
                              {#each framework.related_frameworks as related}
                                <span class="related-tag">{related}</span>
                              {/each}
                            </div>
                          </div>
                        {/if}
                      </div>
                    {/each}
                  </div>
                </div>
              {/each}
            {/if}
          </div>
          
          <div class="report-links">
            <h3>详细报告</h3>
            <div class="report-buttons">
              <a href={getHtmlReportUrl()} target="_blank" class="report-button html-button">
                HTML报告
              </a>
              <a href={getJsonReportUrl()} target="_blank" class="report-button json-button">
                JSON数据
              </a>
            </div>
          </div>
        </div>
      {/if}
    </div>
  {/if}
</div>

<style>
  .task-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
      Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }
  
  header {
    margin-bottom: 2rem;
    border-bottom: 1px solid #eee;
    padding-bottom: 1rem;
  }
  
  .back-link {
    margin-bottom: 1rem;
  }
  
  .back-link a {
    color: #4a90e2;
    text-decoration: none;
  }
  
  .back-link a:hover {
    text-decoration: underline;
  }
  
  h1 {
    font-size: 2.5rem;
    color: #333;
    margin: 0;
  }
  
  .loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 3rem;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .spinner {
    border: 3px solid rgba(0, 0, 0, 0.1);
    border-top: 3px solid #4a90e2;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    margin-bottom: 1rem;
    animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .error-card {
    background-color: #ffebee;
    padding: 2rem;
    border-radius: 8px;
    margin-bottom: 2rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .error-card h2 {
    color: #c62828;
    margin-top: 0;
  }
  
  .error-card button {
    background-color: #4a90e2;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
  }
  
  .task-card {
    background-color: #fff;
    border-radius: 8px;
    padding: 2rem;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .task-header {
    margin-bottom: 2rem;
    border-bottom: 1px solid #eee;
    padding-bottom: 1rem;
  }
  
  .task-header h2 {
    color: #333;
    margin: 0 0 1rem;
    font-size: 1.5rem;
  }
  
  .task-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
  }
  
  .task-time {
    font-size: 0.9rem;
    color: #666;
  }
  
  .status-badge {
    padding: 0.4rem 0.8rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: bold;
    color: white;
  }
  
  .status-pending {
    background-color: #9e9e9e;
  }
  
  .status-processing {
    background-color: #2196f3;
  }
  
  .status-completed {
    background-color: #4caf50;
  }
  
  .status-failed {
    background-color: #f44336;
  }
  
  .progress-section {
    text-align: center;
    padding: 2rem 0;
  }
  
  .progress-bar {
    height: 8px;
    background-color: #e0e0e0;
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 1rem;
  }
  
  .progress-inner {
    height: 100%;
    background-color: #4a90e2;
    border-radius: 4px;
    animation: indeterminate 1.5s infinite ease-in-out;
    width: 50%;
  }
  
  @keyframes indeterminate {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(200%); }
  }
  
  .result-section {
    display: flex;
    flex-direction: column;
    gap: 2rem;
  }
  
  .summary-section pre {
    background-color: #f5f5f5;
    padding: 1rem;
    border-radius: 4px;
    white-space: pre-wrap;
    font-family: monospace;
    line-height: 1.5;
    margin: 0;
  }
  
  .frameworks-section h3,
  .summary-section h3,
  .report-links h3 {
    color: #333;
    margin: 0 0 1rem;
    font-size: 1.5rem;
    border-bottom: 1px solid #eee;
    padding-bottom: 0.5rem;
  }
  
  .category-group {
    margin-bottom: 2rem;
  }
  
  .category-group h4 {
    color: #555;
    margin: 0 0 1rem;
    font-size: 1.2rem;
  }
  
  .frameworks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 1rem;
  }
  
  .framework-card {
    background-color: #f9f9f9;
    border-radius: 6px;
    padding: 1rem;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .framework-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .framework-header h5 {
    margin: 0;
    font-size: 1.1rem;
    color: #333;
  }
  
  .confidence-badge {
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: bold;
    color: white;
  }
  
  .framework-version {
    color: #666;
    font-size: 0.9rem;
  }
  
  .framework-features,
  .related-frameworks {
    margin-top: 0.5rem;
  }
  
  .feature-tags,
  .related-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    margin-top: 0.25rem;
  }
  
  .feature-tag {
    background-color: rgba(74, 144, 226, 0.1);
    color: #4a90e2;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
  }
  
  .related-tag {
    background-color: rgba(156, 39, 176, 0.1);
    color: #9c27b0;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
  }
  
  .report-links {
    margin-top: 1rem;
  }
  
  .report-buttons {
    display: flex;
    gap: 1rem;
  }
  
  .report-button {
    padding: 0.75rem 1.5rem;
    border-radius: 4px;
    font-weight: bold;
    text-decoration: none;
    color: white;
    transition: background-color 0.3s;
  }
  
  .html-button {
    background-color: #4caf50;
  }
  
  .html-button:hover {
    background-color: #388e3c;
  }
  
  .json-button {
    background-color: #ff9800;
  }
  
  .json-button:hover {
    background-color: #f57c00;
  }
  
  .error-section {
    padding: 1.5rem;
    background-color: #ffebee;
    border-radius: 4px;
    margin-top: 1rem;
  }
  
  .error-section h3 {
    color: #c62828;
    margin-top: 0;
  }
</style> 